package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/blogHome")
public class BlogHome extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    // 约定 get /blogHome
    // 使用 application/json 的形式组织数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理前端进入 blogHome 主页的请求
        // 1. 获取博客列表
        BlogDao blogDao = new BlogDao();
        List<Blog> blogList = blogDao.getBlogList();
        // 2. 调用 jackson API , 构造 json 字符数组
        String blogListJson = objectMapper.writeValueAsString(blogList);
        // 3. 返回响应
        resp.setStatus(200);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(blogListJson);
    }
}
